<template>
  <div class="main-center">
    <el-card class="login-card">
      <h2>用户登录</h2>
      <el-form :model="form" :rules="rules" ref="formRef" label-width="80px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="form.username" autocomplete="off" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="form.password" type="password" autocomplete="off" />
        </el-form-item>
        <el-form-item v-if="errorMsg">
          <div style="color: #f56c6c; font-size: 13px;">{{ errorMsg }}</div>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onLogin" :loading="loading">登录</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="text" @click="goRegister('student')" style="margin-right: 16px;">学生注册</el-button>
          <el-button type="text" @click="goRegister('enterprise')">企业注册</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import axios from '@/utils/axios'
import { useUserStore } from '@/store/user'

const router = useRouter()
const userStore = useUserStore()
const formRef = ref()
const loading = ref(false)
const form = ref({ username: '', password: '' })
const rules = {
  username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }]
}
const errorMsg = ref('')

const onLogin = () => {
  formRef.value.validate(async valid => {
    if (!valid) return
    loading.value = true
    errorMsg.value = ''
    try {
      const token = await axios.post('/login', form.value)
      userStore.setToken(token)
      await userStore.fetchUserInfo()
      // 角色分流
      if (userStore.role === 'STUDENT') {
        router.push('/student')
      } else if (userStore.role === 'ENTERPRISE') {
        router.push('/enterprise')
      } else if (userStore.role === 'ADMIN') {
        router.push('/admin')
      } else {
        router.push('/')
      }
    } catch (e) {
      errorMsg.value = e.message || e?.response?.data?.message || '登录失败'
    } finally {
      loading.value = false
    }
  })
}
const goRegister = type => {
  if (type === 'student') router.push('/register/student')
  else router.push('/register/enterprise')
}
</script>

<style scoped>
.login-card {
  max-width: 400px;
  margin: 100px auto;
  padding: 30px 20px;
}
</style> 